package service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import bean.User;
import mapper.Mapper;
import mapper.UserMapper;
import util.JsonTool;

public class UserInfoService extends Mapper<UserMapper>{
	public void alterUser(String qq, String addressee, String tel, String addr, String openid) {
		Map<String, Object> map = new HashMap<>();
		map.put("qq", qq);
		map.put("addressee", addressee);
		map.put("tel", tel);
		map.put("addr", addr);
		map.put("openid", openid);
		
		getMapper().alterUserByOpenid(map);
	}
	public String getUserJsonByQQ(String qq){
		return JsonTool.objectToJson(getMapper().findByQQ(qq));
	}
	public void delUser(String id) {
		int userid = Integer.parseInt(id);
		getMapper().delUser(userid);
	}
	public void lockUser(String id, String lock) {
		int userid = Integer.parseInt(id);
		Map<String, Object> map = new HashMap<>();
		map.put("userid", userid);
		map.put("locked", lock);
		getMapper().lockUser(map);
	}
	// 获取所有用户信息
	public String getAllUser(String username, String qq, String locked, String spage){
		TaskInfoService taskInfoService = new TaskInfoService();
		Map<String, Object> map = new HashMap<>();
		map.put("username", username);
		map.put("qq", qq);
		map.put("locked", locked);
		
//		int page = Integer.parseInt(spage);
//		Page<Object> pageHelper = PageHelper.startPage(page, 10);
		List<User> all = getMapper().findAll(map);
//		long total = pageHelper.getTotal();
		Gson gson = new Gson();
		JsonArray jsonArray = gson.toJsonTree(all).getAsJsonArray();
		// 给每个用户添加总欠款和总付款
		for (Iterator<JsonElement> iterator = jsonArray.iterator(); iterator.hasNext();) {
			JsonElement jsonElement = iterator.next();
			int userid = jsonElement.getAsJsonObject().get("id").getAsInt();
			JsonElement paymoney = gson.toJsonTree(taskInfoService.getPayMoneyJson(userid));
			JsonElement lackmoney = gson.toJsonTree(taskInfoService.getLackMoneyJson(userid));
//			double havemoney = Double.parseDouble(paymoney.getAsString()) - Double.parseDouble(lackmoney.getAsString());
			jsonElement.getAsJsonObject().add("paymoney", paymoney);
			jsonElement.getAsJsonObject().add("lackmoney", lackmoney);
//			jsonElement.getAsJsonObject().addProperty("havemoney", havemoney);
		}
		// 总数
//		String totalJson = "{'total':" + total + "}";
//		JsonObject totalObject = new JsonParser().parse(totalJson).getAsJsonObject();
//		jsonArray.add(totalObject);
		return gson.toJson(jsonArray);
	}
}